<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/lib/jApiController.php';

class UserModelEdit extends jApiControllerEdit{
	protected $editor=false;
	
	public function getValid(){
		include_once $_SERVER['DOCUMENT_ROOT'].'/lib/UserValidator.php';
		return UserValidator::inst();
	}
	
	public function storeSearch($id,$text){
	  $sql='REPLACE INTO search SET s_key_obj=:id, s_ln=:ln, s_text=:text, s_obj_typ=:ch2';
	  $sql_prm=array(':id'=>$id,':ln'=>$this->api->lang,':text'=>$text,':ch2'=>substr($id, 0, 2)  );
		$this->setData($sql, $sql_prm);
		return $rs;
	}
	
	public function authUser($data=array()){
	  if(empty($data) || empty($data['email']) || empty($data['password'])) //throw_error('Auth data not passed',500);
	    return $this->error('Auth data not passed');
	  $sql="SELECT u_id,u_name,u_nameshort,u_createtime,u_email,u_pwd FROM user WHERE u_email=:email AND u_pwd=:pwd";
	  $sql_prm=array(':email'=>$data['email'], ':pwd'=>$data['password']);

	  $t= $this->getData($sql,$sql_prm, true );
	  if(empty($t)) //throw_error('access denied',500);
	  	return $this->error('access denied');
	  
	  $token='tn'.md5($t['u_email'].$t['u_name'].mktime().$t['u_createtime'].$t['u_bdate'].uniqid(''));
	  $now=mktime();
	  $dead=($now+7200); //+2 houers
	  $ip=(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))?$_SERVER['HTTP_X_FORWARDED_FOR']:$_SERVER['REMOTE_ADDR'];

	  //Сохраняю токен
	  $sql="REPLACE INTO token SET t_id=:token, t_key_user=:user, t_set=:set, t_dead=:dead";
	  $sql_prm=array(':token'=>$token, ':user'=>$t['u_id'], ':dead'=>$dead, ':set'=>$now);

   	//echo $sql.'<pre class="debug">'.print_r ( $sql_prm ,true).'</pre>';
	  if(!$this->setData($sql, $sql_prm)) //throw_error('Store token error',500);
	  	return $this->error('Store token error');
	  
	  //Изменяю время последней авторизации
	  $sql="UPDATE user SET u_lastlogin=:now WHERE u_id=:id";
	  $sql_prm=array(':id'=>$t['u_id'], ':now'=>$now);
	  $this->setData($sql, $sql_prm);
	  //Сохраняю IP
	  $sql="REPLACE INTO user_ip SET ui_key_user=:id, ui_ip=INET_ATON(:ip), ui_time=:now"; //INET_ATON INET_NTOA
	  $sql_prm=array(':id'=>$t['u_id'], ':now'=>$now, ':ip'=>$ip);
	  
	  $this->setData($sql, $sql_prm);
	  
	  return array('token'=>$token,'user'=>$t['u_id'],'dead'=>$dead);
	}

	public function getUsrId($model){
	  return 'ur'.md5( $model['u_name'].$model['u_email'].$model['u_bdate'] );
	}
	
	protected function getEditor(){
	  if( !empty( $this->editor ) ) return $this->editor;
		if( empty($this->api->env['_GET']['token']) ) return NULL;
		else{
		  if( !$this->maskID($this->api->env['_GET']['token'],'token') ) return $this->error('get editor: Expected token id');
		  if(!$a=$this->cloneApi( $this->api ))return $this->error('fail clone Api');
		  $editor=$a->get('/byToken/'.$this->api->env['_GET']['token']);
	  	if(empty($editor)) return NULL;
			return $editor;
		}
	}
	
	public function postUser($data=array()){
    $model=array(
      'u_id'=>'',
			'u_type'=>'',
			
			'u_agency'=>'',
			'u_vendor'=>'',
			'u_worker'=>'',
			
			'u_name'=>'',
			'u_nameshort'=>'',
			'u_createtime'=>'',
			'u_email'=>'',
			'u_pwd'=>'',
			'u_country'=>'',
			'u_lock'=>'',
		);

		$data=$this->api->env['_POST'];
		//echo 'conf<pre class="debug">'.print_r ( $this->api->getConfig() ,true).'</pre>'; exit();
  	//$locApi=new jApi( $this->api->getConfig() );
		
		$fields=array();$vals=array();

		$data['u_name']=$data['u_lname'].' '.$data['u_fname'].' '.$data['u_mname'];
		$data['u_nameshort']=$data['u_lname'].' '. mb_strtoupper( mb_substr($data['u_fname'], 0, 1, 'utf8') .'.'.mb_substr($data['u_mname'], 0, 1, 'utf8').'.' , 'utf8');
		$data['u_createtime']=mktime();
		$data['u_id']=$this->getUsrId($data);

    if( !$this->getValid()->postUser($data) )
      return $this->error( 'user validation errors: '.$this->getValid()->getValidationErrors() );

		//Есть ли такой пользователь
		if(!$a=$this->cloneApi( $this->api ))return $this->error('fail clone Api');

		$tst=$a->get('/user/'.$data['u_id']);
		
		$mode='insert';
		if(!empty($tst)){
			if( !$editor=$this->getEditor() ) return $this->error('user exists');
		  else{
		    if(
					$editor['u_id']==$data['u_id'] ||
					$editor['u_type']=='adm'
				)	$mode='update';
			}
		}
	
	  if( $mode=='insert' ){
			$tst=$this->makeGet('/byEmail/'.$data['u_email']);
			if(!empty($tst))	return $this->error('user with posted email exists');
			$data['u_lock']=1;
		}
		
		if(!empty($data['u_type'])){
			switch($data['u_type']){
			  case 'geo':
			  case 'adm':
			    if(!$editor=$this->getEditor())	return $this->error('Operation require auth');
					if($editor['u_type']!='adm')		return $this->error('Operation require admin auth. Access denied!');
					break;
			  default: $data['u_type']='usr';
			}
		}

		if(!empty($data['u_geo'])) $this->setUserGeo( $data );
		unset($data['u_geo']);

		$isProfileData=false; foreach( $data as $k=>$v )
		  if( !empty($v) && substr($k, 0,2)=='p_' ) {
				$isProfileData=true; break;
			}
		
		/*
		$isCompanyData=false; foreach( $data as $k=>$v )
		  if( !empty($v) && substr($k, 0,2)=='cmp_' ) {
				$isCompanyData=true; break;
			}
		if( $isCompanyData ) $this->postCompany( $data );
		*/

		switch($mode){
		  case 'insert': $sql="INSERT INTO user SET {fields}"; break;
		  case 'update': $sql="UPDATE user SET {fields} WHERE u_id=:u_id"; break;
		  default: return $this->error('Fail mode detect');
		} 
	  foreach($model as $k=>$v){
			$fields[]=$k.'=:'.$k;
	    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}
		$sql=str_replace('{fields}',implode(',', $fields),$sql);
	  $this->setData($sql, $vals);

		$searchText=$data['u_name'].' '.$data['u_email'].' '.$data['u_id'];
	  $this->storeSearch($data['u_id'], $searchText);

    if( $isProfileData ) $this->postProfile( $data );

	  return array('result'=>'success','info'=> $this->getErrors() ,'model'=>$data);
	}
	
	public function setUserGeo($data=array()){
	  if(empty($data['u_id'])) return $this->error('set geo: user ID expected');
	  if(empty($data['u_geo'])) return $this->error('set geo: geo expected');
	  if(!is_array($data['u_geo']) ) $data['u_geo']=array($data['u_geo']);
	  
	  $sql="INSERT INTO user2geo VALUES ";
	  $fields=array(); $vals=array();
	  for( $i=0, $cnt=count($data['u_geo']); $i<$cnt; $i++  ){
	    if(
				strpos('rg,ct,ua', substr($data['u_geo'][$i], 0,2))===false ||
	      strlen($data['u_geo'][$i])!=34
			){
				$this->error('set geo: "'.$data['u_geo'][$i].'" is not valid geo id');
				continue;
			}
			$fields[]='(:id,:geo'.$i.')';
			$vals[':geo'.$i]=$data['u_geo'][$i];
		}
		if(empty($fields)) return $this->error('set geo: nothing to save');
		$sql.=implode(',', $fields);
		
	  $sqlDel="DELETE FROM user2geo WHERE u2g_key_user=:id";
    $this->setData($sqlDel, array(':id'=>$data['u_id']) );
    
    $vals[':id']=$data['u_id'];
    $this->setData( $sql, $vals );
	  return array('result'=>'success','info'=>'' ,'model'=>$data);
	}
	
	public function postProfile($data=array()){
    $model=array(
      'p_key'=>'',
      'p_createtime'=>'',
			'p_url'=>'',
			'p_pasport'=>'',
			'p_phone'=>'',
			'p_bdate'=>'',
			'p_gender'=>'',
			'p_medicalBook'=>'',
		);
		$fields=array();$vals=array();

		if(empty($data['p_key']))
		  if(!empty($data['u_id'])) $data['p_key']=$data['u_id'];
		  else  return $this->error('post profile: expected profile or user ID info');
		if(empty($data['p_url']))$data['p_url']=$data['p_key'];

    if( !$this->getValid()->postProfile($data) )
			return $this->error('post profile: '.$this->getValid()->getValidationErrors());

		$sql="REPLACE INTO profile SET ";
	  foreach($model as $k=>$v){
			$fields[]=$k.'=:'.$k;
	    $vals[':'.$k]=(isset($data[$k]))?$data[$k]:$v;
		}
		if(empty($fields)) return $this->error('post profile: nothing to save');
		$sql.=implode(',', $fields);
	  if(!$rs=$this->setData($sql, $vals)) return $this->error('post profile: '.$this->getError());

	  return array('result'=>'success','info'=> '' ,'model'=>$data);
	}
}
?>